package storage

import (
	"go.etcd.io/bbolt"
	"log"
	"berry-tv/file"
)

type DB *bbolt.DB

type MediaInfo struct {
	name string
	link string
}

func check(err error) {
	if err != nil {
		log.Panic("check: ", err)
	}
}

// return db, created
// created: database created
func Open(dbPath string) (*bbolt.DB, bool) {
	created := false
	if !file.Exist(dbPath) {
		created = true
	}
	db, err := bbolt.Open(dbPath, 0666, nil)
	check(err)

	return db, created
}

func Close(db *bbolt.DB) {
	db.Close()
}

func CreateBucket(db *bbolt.DB, name string) bool {
	err := db.Update(func(tx *bbolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(name))
		if err != nil {
			log.Fatal(err)
			return err
		}
		return nil
	})
	check(err)
	return true
}
